import {
    selectFontList,
    getCssData,
} from "../../common/js/practice_set.js";

import {
    post
} from "@/common/js/http.js";

let app = getApp(),
    that = null,
    helper = app.globalData.helper;
export default {
    data() {
        return {
            CustomBar: this.CustomBar,
            listData: [],
            backgroundData: [],
            title: '',
            id: 0,
            openSetModal: false, // 开启设置模态框
            openAiExplanationModal: false, // 开启AI解析模态框
            mainType: 0,
            maxPage: 0,
            questionType: 0,
            isContinue: 2,
            currentPage: 1,
            currentAction: 0,
            selectModel: ['刷题模式', '背题模式'],
            selectModelIndex: 0,
            isLoad: false,
            endId: 0,
            limit: 10,
            swiperCurrent: 0,
            doExamList: [],
            isAutoNext: false,
            isNightMode: false,
            isDarkMode: false,
            isAutoCorrectNext: false,
            isShowAutoNextDialog: true,
            extend_id: '',
            pageSelectList: '',
            selectPage: '',
            questionFont: 1,
            questionCount: 0,
            selectFontList: selectFontList,
            moreActionNavIndex: 0,
            moreActionNavList: ['题目操作', '答题设置', '显示设置'],
            answerSheetStatus: [],
            cssData: {},
            openAnswerCardModal: false, // 答题卡弹窗显示控制
            countStats: [0, 0, 0, 0], // [正确数量, 错误数量, 已答题数量, 未答题数量]
        };
    },
    onLoad(options) {
        that = this;
        that.id = options.id;
        that.title = options.title;
        that.extend_id = helper.variableDefalut(options.extend_id, 0);
        that.mainType = options.mainType;
        that.maxPage = options.max_page || 0;
        that.questionType = options.question_type || 0;
        that.questionCount = options.question_count || 0;
        that.isAutoCorrectNext = Boolean(uni.getStorageSync(app.globalData.config.storage.practiceCorrectNextKey));
        that.isAutoNext = Boolean(uni.getStorageSync(app.globalData.config.storage.practiceAllNextKey));
        that.isNightMode = Boolean(uni.getStorageSync(app.globalData.config.storage.practiceIsNightKey));
        that.isDarkMode = Boolean(uni.getStorageSync(app.globalData.config.storage.practiceIsNightKey));
        that.isShowAutoNextDialog = uni.getStorageSync(app.globalData.config.storage.practiceNextDialogKey);
        app.globalData.showShareMenu();
        that.initAnswerSheet();
        that.getContinueData();
    },
    onShow() {
        that.initCss();
    },
    onShareAppMessage() {
        let item = that.listData[that.swiperCurrent];
        let shareConfig = app.globalData.getShareConfig();
        shareConfig.title = item.questionAsk;
        shareConfig.path = '/pages/practice/question/detail?id=' + item.id;
        return shareConfig;
    },
    methods: {
        // 初始化答题卡方法
        async initAnswerSheet() {

            let res = await post('question/getAnswerCard', {
                id: that.id,
                type: that.mainType,
                extend_id: that.extend_id,
                question_type: that.questionType
            });
            let answerCard = res.data;
            console.log(answerCard);

            // 初始化答题卡逻辑
            let answerSheetStatus = [];
            let limit = that.limit || 10; // 每页题目数量，默认10

            // 使用API返回的答题卡数据
            if (answerCard && answerCard.answer_card && answerCard.answer_card.length > 0) {
                // 遍历API返回的答题卡数据
                answerCard.answer_card.forEach((item, i) => {
                    // 计算当前题目在第几页
                    let questionPage = Math.floor(i / limit) + 1;
                    // 计算当前题目在当前页的索引（从1开始）
                    let questionIndex = (i % limit) + 1;

                    answerSheetStatus.push({
                        index: item.index,
                        questionPage: questionPage,
                        questionIndex: questionIndex,
                        questionId: item.id,
                        status: item.status // 直接使用API返回的状态值：0=未答题, 1=正确, 2=错误
                    });
                });
            }

            // 使用Vue的方式更新数组
            that.$set(that, 'answerSheetStatus', answerSheetStatus);

            // 更新统计信息
            if (answerCard) {
                let countStats = [
                    answerCard.right_count || 0,
                    answerCard.error_count || 0,
                    answerCard.answered_count || 0,
                    answerCard.no_answer_count || 0
                ];
                that.$set(that, 'countStats', countStats);
            }
        },

        /**
         * 更新答题卡状态
         * @param {Number} currentQuestionIndex 当前题目在页面上的索引（不传则更新整页）
         */
        updateAnswerCardStatus(currentQuestionIndex = null) {
            if (!that.answerSheetStatus || that.answerSheetStatus.length === 0) return;

            // 如果提供了当前题目索引，只更新该题目
            if (currentQuestionIndex !== null && that.listData && that.listData.length > 0) {
                // 确保索引有效
                if (currentQuestionIndex >= 0 && currentQuestionIndex < that.listData.length) {
                    // 获取当前题目
                    const question = that.listData[currentQuestionIndex];

                    // 计算题目在答题卡中的实际位置
                    const answerSheetIndex = (that.currentPage - 1) * that.limit + currentQuestionIndex;

                    // 确保索引在有效范围内
                    if (answerSheetIndex < that.answerSheetStatus.length) {
                        // 根据题目的作答状态确定答题卡状态
                        let newStatus = 0;
                        if (question.is_correct === 1) {
                            newStatus = 1; // 正确
                        } else if (question.is_correct === 2) {
                            newStatus = 2; // 错误
                        } else if (question.select_answer && question.select_answer.length > 0) {
                            newStatus = 0; // 已作答但未判断正误
                        }

                        // 使用Vue的$set方法更新数组元素，确保响应式更新
                        that.$set(that.answerSheetStatus[answerSheetIndex], 'status', newStatus);
                    }
                }
            }

            // 重新计算所有统计数据
            that.recalculateStats();
        },

        // 重新计算统计数据
        recalculateStats() {
            let countStats = [0, 0, 0, 0]; // [正确数量, 错误数量, 已答题数量, 未答题数量]

            // 遍历所有答题卡状态，统计各类题目数量
            that.answerSheetStatus.forEach(item => {
                if (item.status === 1) {
                    countStats[0]++; // 正确题目
                    countStats[2]++; // 已答题
                } else if (item.status === 2) {
                    countStats[1]++; // 错误题目
                    countStats[2]++; // 已答题
                } else if (item.status === 0) {
                    countStats[3]++; // 未答题
                }
            });

            // 更新统计数据 - 使用Vue的方式更新数组
            that.$set(that, 'countStats', countStats);
        },
        onLongPress(e) {
            uni.setClipboardData({
                data: e,
                success() {
                    app.showToast('复制成功');
                },
                fail(res) {
                    console.log(res);
                }
            });
        },
        onCleanQuestionTap() {
            uni.showModal({
                title: '提示',
                content: '确认清空答题记录',
                showCancel: true,
                success: (t) => {
                    if (t.confirm) {
                        that.clearAnswer(0);
                        that.openSetModal = false;
                    }
                }
            });
        },
        onCleanErrorQuestionTap() {
            uni.showModal({
                title: '提示',
                content: '确认清空错题记录',
                showCancel: true,
                success: (t) => {
                    if (t.confirm) {
                        that.clearAnswer(2);
                        that.openSetModal = false;
                    }
                }
            });
        },
        moreActionIndexTap(options) {
            that.moreActionNavIndex = options.currentTarget.dataset.index
        },
        initCss() {
            let isDarkMode = that.isDarkMode;
            let questionFont = uni.getStorageSync(app.globalData.config.storage.practiceQuestionFontKey);
            questionFont = questionFont == '' ? 1 : questionFont;
            that.questionFont = questionFont;
            that.cssData = getCssData(questionFont, isDarkMode);
        },
        selectModelTap(options) {
            that.selectModelIndex = options.currentTarget.dataset.id;
            that.listData = that.formatQuestionList(that.listData, false);
        },
        switchQuestionTap(options) {
            console.log(options.currentTarget.dataset.type)
            let current = options.detail.current;
            that.swiperCurrent = current + 1;
        },
        transitionTap(options) {
            let dx = options.detail.dx;
            let action = dx > 30 ? 2 : dx < -30 ? 1 : 0;
            let maxPage = that.maxPage;
            let currentPage = that.currentPage;
            let swiperCurrent = that.swiperCurrent;
            let isLoad = that.isLoad;
            let listDataLength = that.listData.length;
            if (action === 0) {
                return;
            }
            if (isLoad === true) {
                return;
            }
            let canLoad = (action == 1 && swiperCurrent == 0) || (action == 2 && swiperCurrent == listDataLength -
                1);
            if (!canLoad) {
                return;
            }
            let donLoad = (action === 1 && currentPage == 1) || (action == 2 && that.currentPage == maxPage);
            if (donLoad) {
                return;
            }
            that.currentAction = action;
        },
        animationfinishTap(options) {
            if ('touch' == options.detail.source) {
                let current = options.detail.current;
                let currentPage = that.currentPage;
                let currentAction = that.currentAction;
                that.swiperCurrent = current;

                if (current == that.listData.length - 1 && currentPage == that.maxPage) {
                    app.showToast('最后一道题啦');
                }
                if (currentAction > 0) {
                    that.currentPage = currentAction === 1 ? currentPage - 1 : currentPage + 1;
                    that.getQuestion(currentAction);
                }
            }
        },
        setQuestionDirectionTap(current) {
            let nextCurrentPage = that.currentPage;
            let nextSwiperCurrent = that.swiperCurrent;
            if (current == 1) {
                if (nextSwiperCurrent == 0) {
                    nextCurrentPage--;
                    if (nextCurrentPage == 0) {
                        app.showToast('没有上一题啦');
                        return;
                    }
                    that.currentPage = nextCurrentPage;
                    that.getQuestion(1);
                } else {
                    that.swiperCurrent = nextSwiperCurrent - 1;
                }
            } else {
                if (nextSwiperCurrent == that.listData.length - 1) {
                    nextCurrentPage++;
                    if (nextCurrentPage > that.maxPage) {
                        app.showToast('没有下一题啦');
                        return;
                    }
                    that.currentPage = nextCurrentPage;
                    that.getQuestion(2);
                } else {
                    that.swiperCurrent = nextSwiperCurrent + 1;
                }
            }
        },
        getContinueData() {
            let e = that;
            post('question/is_continue', {
                id: e.id,
                type: e.mainType,
                extend_id: e.extend_id,
                question_type: e.questionType
            })
                .then((t) => {
                    let e = t.data;

                    if (1 == e.is_continue) {
                        uni.showModal({
                            title: '提示',
                            content: '检测到上次做题记录，是否继续答题',
                            showCancel: true,
                            cancelText: '重新答题',
                            confirmText: '继续答题',
                            success: (t) => {
                                if (t.confirm) {
                                    that.currentPage = e.last_question_page;
                                    that.getQuestion(2, e.last_question_id);
                                } else {
                                    if (that.mainType == 2 || that.mainType == 3) {
                                        //收藏和错题不需要清空
                                        that.getQuestion(2, 0);
                                    } else {
                                        that.clearAnswer();
                                    }
                                }
                            }
                        });
                    } else {
                        that.getQuestion(2, 0);
                    }
                })
                .catch((a) => {
                    console.log(a);
                    app.showToast('获取答题记录失败');
                });
        },
        clearAnswer(status) {
            post('question/clear', {
                id: that.id,
                status: status,
                type: that.mainType,
                extend_id: that.extend_id,
                question_type: that.questionType
            })
                .then((response) => {
                    that.getQuestion(2, 0);
                })
                .catch((err) => {
                    console.log(err);
                });
        },

        getQuestion(type = 2, jumpToId = 0, jumpToIndex = null) {
            //标记加载中
            that.isLoad = true;
            that.currentAction = 0;

            let data = that;
            post('v3/get_topic', {
                id: data.id,
                type: data.mainType,
                extend_id: data.extend_id,
                question_type: data.questionType,
                page: data.currentPage || 1,
                limit: data.limit
            })
                .then((res) => {
                    let list = that.formatQuestionList(res.data.question_list, true);
                    let background = res.data.question_background;
                    that.$set(that, 'backgroundData', background);

                    if (list.length > 0) {
                        that.$set(that, 'listData', list);

                        // 设置默认的swiperCurrent
                        if (jumpToIndex !== null && jumpToIndex >= 0 && jumpToIndex < list.length) {
                            // 如果指定了jumpToIndex，直接跳转到该索引位置
                            that.swiperCurrent = jumpToIndex;
                        } else {
                            // 否则使用默认的索引位置
                            let newSwiperCurrent = type == 2 ? 0 : that.listData.length - 1;
                            that.swiperCurrent = newSwiperCurrent;
                        }
                    }

                    // 如果有指定跳转题目ID，则尝试跳转到该题目
                    if (jumpToId > 0 && jumpToIndex === null) {
                        const targetIndex = that.listData.findIndex(item => item && item.id === jumpToId);
                        if (targetIndex !== -1) {
                            that.swiperCurrent = targetIndex;
                        }
                    }
                })
                .catch((res) => {
                    console.log(res);
                })
                .finally(() => {
                    //保存答题记录
                    that.saveAnswers(1); //标记数据加载完成
                    setTimeout(() => {
                        that.isLoad = false;
                    }, 3000);
                });
        },

        /**
         * 格式化题目列表
         * @param {*} list 题目列表
         * @param {*} isFirst 是否是第一次加载
         * @returns 
         */
        formatQuestionList(list, isFirst) {
            for (var i = 0; i < list.length; i++) {
                let type = list[i]['type']

                // 添加support_answer字段,判断是否支持答题
                list[i]['support_answer'] = app.globalData.practice.checkSupportAnswer(type);
                
                // 初始化AI解析字段
                if (!list[i].hasOwnProperty('aiExplanation')) {
                    list[i]['aiExplanation'] = '';
                }

                // 用于支持切换答题模式
                if (type < 4) {
                    let correctOption = list[i]['correctOption'];
                    list[i]['correctOptionArr'] = app.globalData.practice.buildAnswerOption(correctOption);
                    if (that.selectModelIndex == 1) {
                        // 背题模式
                        list[i]['select_answer'] = correctOption;
                        list[i]['is_correct'] = 1;
                    } else {
                        // 刷题模式
                        if (!isFirst) {
                            list[i]['select_answer'] = "";
                            list[i]['is_correct'] = 0;
                        }
                    }
                }
            }
            return list;
        },

        /**
         * 记录答题并检查是否需要上传题目数据
         * @param {Object} question 题目对象
         */
        checkAndQueueForUpload(question) {
            that.doExamList.push(question);
            if (this.doExamList.length >= 10) {
                that.saveAnswers();
            }
        },


        handleBeforeBack() {
            console.log('handleBeforeBack');
            that.saveAnswers(2);
        },

        /**
         *  保存答案到服务器
         * @param {*} action  1.普通保存 2.返回保存 3.交卷保存
         */
        async saveAnswers(action) {
            if (this.doExamList.length == 0) {
                return;
            }

            // 创建上传数据
            let uploadData = [];
            this.doExamList.forEach(item => {
                const answerData = {
                    course_id: item.course_id,
                    extend_id: item.extend_id,
                    question_id: item.id,
                    question_type: item.type,
                    question_page: item.page,
                    question_correct: item.is_correct,
                    question_answer: item.type == 2 ?
                        item.select_answer.join('') : item.select_answer
                };
                uploadData.push(answerData);
            });

            // 保存答题数据
            await post('question/save_answer', {
                course_id: that.id,
                source: that.mainType,
                answer_data: uploadData
            });

            // 清空答题数据
            that.doExamList = [];
            app.showToast('保存成功');

            // 跳转到答题结果页
            if (action == 3) {
                that.toResultPage();
            }

        },



        /**
         * 单选题点击事件
         * @param {*} event 
         */
        singleSelectTap(event) {
            // 获取当前题目
            const index = that.swiperCurrent;
            const currentQuestion = that.listData?.[index];
            if (!currentQuestion || currentQuestion.is_correct !== 0) {
                return;
            }

            // 获取选择答案
            const selectedAnswer = event.currentTarget.dataset.answer;
            const isCorrect = selectedAnswer === currentQuestion.correctOption;
            const correctStatus = isCorrect ? 1 : 2;

            // 更新题目状态
            currentQuestion.is_correct = correctStatus;
            currentQuestion.select_answer = selectedAnswer;
            that.$set(that.listData, index, currentQuestion);

            // 更新答题卡状态
            that.updateAnswerCardStatus(index);

            // 记录答题并处理下一题
            that.checkAndQueueForUpload(currentQuestion);
            that.skipNextQuestion(correctStatus);
        },

        /**
         * 多选题点击选型事件
         * @param {*} event 
         */
        multipleSelectTap(event) {
            // 获取当前题目
            const index = that.swiperCurrent;
            const currentQuestion = that.listData?.[index];

            // 如果没有题目或题目已经回答过，则直接返回
            if (!currentQuestion || currentQuestion.is_correct !== 0) {
                return;
            }

            // 获取选项索引
            const optionIndex = event.currentTarget.dataset.index;

            // 获取选项值
            const optionValue = app.globalData.practice.options[optionIndex];

            // 创建新的选择答案数组
            const newSelectAnswer = currentQuestion.select_answer ? [...currentQuestion.select_answer] : new Array(6);

            // 切换选项状态
            newSelectAnswer[optionIndex] = newSelectAnswer[optionIndex] === optionValue ? '' : optionValue;

            // 更新题目的选择答案
            currentQuestion.select_answer = newSelectAnswer;

            // 使用Vue的$set方法更新数组元素
            that.$set(that.listData, index, currentQuestion);
        },

        /**
         * 多选题提交事件
         * @param {*} event 
         */
        multipleSelectCommitTap(event) {
            // 获取当前题目
            const index = that.swiperCurrent;
            const currentQuestion = that.listData?.[index];

            // 如果没有题目或题目已经回答过，则直接返回
            if (!currentQuestion || currentQuestion.is_correct !== 0) {
                return;
            }

            // 如果是多选题且还没有初始化correctOptionArr，先进行初始化
            if (currentQuestion.type === app.globalData.practice.topicType.multi && !currentQuestion.correctOptionArr) {
                // 处理正确选项
                const correctOptionArray = new Array(6);
                const correctOption = currentQuestion.correctOption || '';

                // 使用扩展运算符和字符串方法更简洁地处理
                [...correctOption].forEach(optionChar => {
                    const index = 'ABCDEF'.indexOf(optionChar);
                    if (index !== -1) {
                        correctOptionArray[index] = optionChar;
                    }
                });

                const selectedOptionArray = new Array(6);

                // 处理已选择的答案
                if (currentQuestion.select_answer) {
                    [...currentQuestion.select_answer].forEach(selectedChar => {
                        const index = 'ABCDEF'.indexOf(selectedChar);
                        if (index !== -1) {
                            selectedOptionArray[index] = selectedChar;
                        }
                    });
                }

                // 更新当前题目对象
                currentQuestion.correctOptionArr = correctOptionArray;
                currentQuestion.select_answer = selectedOptionArray;
            }

            // 获取选择答案
            const selectedAnswer = currentQuestion.select_answer || [];
            const correctOptionArr = currentQuestion.correctOptionArr || [];

            // 检查是否有选择答案
            if (!selectedAnswer.filter(Boolean).length) {
                app.showToast('请选择答案');
                return;
            }

            // 判断答案是否正确
            let isAllCorrect = true;

            // 检查选项数量是否一致
            if (selectedAnswer.filter(Boolean).length !== correctOptionArr.filter(Boolean).length) {
                isAllCorrect = false;
            } else {
                // 检查每个选项是否正确
                for (const answer of selectedAnswer.filter(Boolean)) {
                    if (!correctOptionArr.includes(answer)) {
                        isAllCorrect = false;
                        break;
                    }
                }
            }

            // 判断答案是否正确
            const correctStatus = isAllCorrect ? 1 : 2;

            // 更新题目状态
            currentQuestion.is_correct = correctStatus;

            // 使用Vue的$set方法更新数组元素
            that.$set(that.listData, index, currentQuestion);

            // 更新答题卡状态
            that.updateAnswerCardStatus(index);

            // 记录答题并处理下一题
            that.checkAndQueueForUpload(currentQuestion);
            that.skipNextQuestion(correctStatus);
        },

        /**
         * 跳转下一题
         * @param {*} correctStatus 
         */
        skipNextQuestion(correctStatus) {
            if (0 != this.listData.length) {
                let currentIndex = that.swiperCurrent;

                // Show dialog if not shown before
                if (!that.isShowAutoNextDialog) {
                    that.isShowAutoNextDialog = true;
                    uni.showModal({
                        title: '提示',
                        content: '可在底部设置是否自动切换下一题',
                        cancelText: '不再提示',
                        confirmText: '知道了',
                        success: (result) => {
                            if (result.cancel) {
                                uni.setStorageSync(app.globalData.config.storage.practiceNextDialogKey,
                                    true);
                            }
                        }
                    });
                }

                // Auto-advance to next question if conditions are met
                if (currentIndex != that.listData.length - 1 &&
                    (that.isAutoNext || (that.isAutoCorrectNext && 1 == correctStatus))) {
                    that.swiperCurrent = currentIndex + 1;
                }
            }
        },
        openQuestionImagesTap() {
            let item = that.listData[that.swiperCurrent];
            uni.previewImage({
                urls: item.question_images,
                referrerPolicy: 'origin',
                longPressActions: {
                    itemList: ['发送给朋友', '保存图片', '收藏'],
                    success: (data) => {
                        console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
                    },
                    fail: (err) => {
                        console.log(err.errMsg);
                    }
                }
            });
        },
        onOpenSetTap() {
            that.openSetModal = true;
        },
        onCloseSetTap() {
            that.openSetModal = false;
        },
        onCollectTap() {
            if (that.listData.length === 0) return;

            // 获取当前题目
            const currentQuestion = that.listData[that.swiperCurrent];
            if (!currentQuestion) return;

            // 切换收藏状态
            const newCollectionStatus = currentQuestion.isCollection === 1 ? 2 : 1;
            currentQuestion.isCollection = newCollectionStatus;

            // 发送收藏请求
            post('question/collect', {
                id: currentQuestion.id,
                type: newCollectionStatus
            })
                .then((response) => {
                    app.showToast(response.message);

                    // 使用Vue的$set方法更新数组元素
                    that.$set(that.listData, that.swiperCurrent, currentQuestion);
                })
                .catch((error) => {
                    app.showToast('收藏出错');
                    console.log(error);
                });
        },

        /**
         * 提交试题
         */
        commitTap() {
            if (that.listData.length == 0) {
                app.showToast('当前题目数据异常');
                return;
            }

            if (that.mainType == app.globalData.practice.mainType.coll) {
                app.showToast('收藏练习不可以交卷');
                return;
            }

            if (that.mainType == app.globalData.practice.mainType.error) {
                app.showToast('错题练习不可以交卷');
                return;
            }

            uni.showModal({
                title: '保存',
                content: '保存本次答题记录~',
                showCancel: true,
                cancelText: '取消',
                confirmText: '确定',
                success: (action) => {
                    if (action.confirm) {
                        that.saveAnswers(3);
                    }
                }
            });
        },

        toResultPage() {
            let options = that;
            uni.navigateTo({
                url: './result/result?id=' +
                    options.id +
                    '&extend_id=' +
                    options.extend_id +
                    '&mainType=' +
                    options.mainType +
                    '&question_type=' +
                    options.questionType
            });
        },

        /**
         * 题目纠错
         * @param {Object} e
         */
        onFeedbackTap() {
            if (0 != that.listData.length) {
                let i = that.listData[that.swiperCurrent];

                if (0 != that.listData.length) {
                    uni.navigateTo({
                        url: './feedback/feedback?mainType=' + i.mainType + '&id=' + i.id
                    });
                }
            }
        },

        nightModeTap() {
            let isNightMode = !that.isNightMode;
            that.isNightMode = isNightMode;
            that.isDarkMode = isNightMode;
            uni.setStorageSync(app.globalData.config.storage.practiceIsNightKey, isNightMode);
            that.initCss()
        },

        toggleDarkMode(e) {
            let isDarkMode = e.detail.value;
            that.isDarkMode = isDarkMode;
            that.isNightMode = isDarkMode;
            uni.setStorageSync(app.globalData.config.storage.practiceIsNightKey, isDarkMode);
            that.initCss()
        },
        autoCorrectNextTap() {
            let isAutoCorrectNext = !that.isAutoCorrectNext;
            that.isAutoCorrectNext = isAutoCorrectNext;
            uni.setStorageSync(app.globalData.config.storage.practiceCorrectNextKey, isAutoCorrectNext);
        },
        autoNextTap() {
            let isAutoNext = !that.isAutoNext;
            that.isAutoNext = isAutoNext;
            uni.setStorageSync(app.globalData.config.storage.practiceAllNextKey, isAutoNext);
        },
        setQuestionFontTap(e) {
            that.questionFont = e.detail.value;
            uni.setStorageSync(app.globalData.config.storage.practiceQuestionFontKey, e.detail.value);
            that.initCss();
        },

        /**
         * 显示不支持作答题目的答案
         */
        toggleUnsupportedAnswers() {
            // 获取当前题目
            const index = that.swiperCurrent;
            const currentQuestion = that.listData?.[index];
            if (!currentQuestion) {
                return;
            }

            // 直接标记答题正确
            currentQuestion.is_correct = 1;
            that.$set(that.listData, index, currentQuestion);

            // 更新答题卡状态
            that.updateAnswerCardStatus(index);

            // 记录答题
            that.checkAndQueueForUpload(currentQuestion);
        },

        async aiExplanationTap(status) {
            //获取题目信息
            let item = that.listData[that.swiperCurrent];

            //获取题目AI解析
            var aiExplanation = item.aiExplanation;

            //判断是否需要生成ai解析任务
            if (status == true && aiExplanation == '') {
                let res = await app.globalData.service.aiExplanation({
                    id: item.id
                });
                if (res.data.business_code == 1) {
                    //生成中
                    app.showToast(res.message);
                    return;
                } else {
                    // 生成完成
                    aiExplanation = res.data.business_message;
                }
            }

            //清空AI输入内容
            that.listData[that.swiperCurrent].aiExplanation = '';

            //显示或者关闭模态框
            that.openAiExplanationModal = status;

            //定时任务定时提取文本
            app.startInterval(() => {
                if (aiExplanation.length == 0) {
                    app.stopInterval();
                    return;
                }
                let firstChar = aiExplanation[0];
                aiExplanation = aiExplanation.slice(1);
                that.listData[that.swiperCurrent].aiExplanation += firstChar;
            }, 50);
        },
        openAnswerCardTap() {
            that.openAnswerCardModal = true;

            // 使用setTimeout确保DOM更新后再执行滚动操作
            setTimeout(() => {
                // 重新计算统计数据，确保数据最新
                that.recalculateStats();

                // 强制更新视图
                that.$forceUpdate();
            }, 50);
        },
        closeAnswerCardTap() {
            that.openAnswerCardModal = false;
        },
        // 答题卡按钮点击事件
        answerCardItemTap(item) {
            // 关闭答题卡弹窗
            that.closeAnswerCardTap();

            // 如果当前页不是题目所在页，需要先切换到对应页面
            if (that.currentPage !== item.questionPage) {
                that.currentPage = item.questionPage;

                // 如果有questionId，使用ID进行跳转
                if (item.questionId) {
                    that.getQuestion(2, item.questionId);
                } else {
                    // 否则使用索引进行跳转
                    that.getQuestion(2, 0, item.questionIndex - 1);
                }
            } else {
                // 如果已经在正确的页面，只需要更新swiperCurrent即可
                if (item.questionIndex - 1 >= 0 && item.questionIndex - 1 < that.listData.length) {
                    that.swiperCurrent = item.questionIndex - 1;
                }
            }
        },
    }
};